package com.dev.toolkit.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dev.toolkit.config.ds.DbConnectionInfo;
import com.dev.toolkit.domain.entity.DatabaseConfigEntity2;
import com.dev.toolkit.repository.DatabaseConfigMapper2;
import com.dev.toolkit.service.IDatabaseConfigService2;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author ZhuYouBin
 * @version 1.0.0
 * @date 2024/06/05 16:56
 * @description 数据库连接配置信息
 */
@Service
public class DatabaseConfigService2 extends ServiceImpl<DatabaseConfigMapper2, DatabaseConfigEntity2> implements IDatabaseConfigService2 {

    @Override
    public void saveOrUpdateDbConfig(DatabaseConfigEntity2 entity2) {
        // 名称不能重复
        LambdaQueryWrapper<DatabaseConfigEntity2> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(DatabaseConfigEntity2::getName, entity2.getName());
        wrapper.ne(entity2.getId() != null, DatabaseConfigEntity2::getId, entity2.getId());
        if (this.count(wrapper) > 0) {
            throw new RuntimeException("数据源名称不能重复");
        }
        entity2.setCreateTime(new Date());
        this.saveOrUpdate(entity2);
    }

    @Override
    public List<DatabaseConfigEntity2> getDbConfigList(String searchParam) {
        LambdaQueryWrapper<DatabaseConfigEntity2> wrapper = Wrappers.lambdaQuery();
        wrapper.like(StrUtil.isNotEmpty(searchParam), DatabaseConfigEntity2::getName, searchParam);
        return this.list(wrapper);
    }

    @Override
    public DbConnectionInfo getDbConfigByName(String name) {
        LambdaQueryWrapper<DatabaseConfigEntity2> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(DatabaseConfigEntity2::getName, name);
        DatabaseConfigEntity2 entity2 = this.getOne(wrapper);
        if (entity2 == null) {
            return null;
        }
        DbConnectionInfo info = new DbConnectionInfo();
        BeanUtils.copyProperties(entity2, info);
        return info;
    }
}